package com.weiwei.diancan.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.weiwei.diancan.Contant.Config;
import com.weiwei.diancan.Contant.ConfigMethod;
import com.weiwei.diancan.MyApplicatin;
import com.weiwei.diancan.R;
import com.weiwei.diancan.adapter.HomeAdapter;
import com.weiwei.diancan.adapter.MenuAdapter;
import com.weiwei.diancan.base.BaseActivity;
import com.weiwei.diancan.bean.LoginBean;
import com.weiwei.diancan.bean.TabBean;
import com.weiwei.diancan.bean.WaterInfo;
import com.weiwei.diancan.cache.CacheConfig;
import com.weiwei.diancan.http.RetrofitFactory;
import com.weiwei.diancan.service.GetInfoService;
import com.weiwei.diancan.service.UpdataService;
import com.weiwei.diancan.utils.HttpUtils;
import com.weiwei.diancan.utils.LoggerUtils;
import com.weiwei.diancan.utils.PessmionUtils;
import com.weiwei.diancan.utils.VersionUtils;
import com.weiwei.diancan.utils.ViewGetTextUtils;
import com.weiwei.diancan.view.EmptyLayout;
import com.weiwei.diancan.view.HuanZhuoDialog;
import com.weiwei.diancan.view.LoginDialog;
import com.weiwei.diancan.view.PayPopwindow;
import com.weiwei.diancan.view.SimpleSwipeRefreshLayout;
import com.weiwei.diancan.view.UpdateDialog;
import com.weiwei.diancan.view.VersionDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import weiwei.com.weiweilibrary.views.ToastUtil;

public class Main1Activity extends BaseActivity {

    private PayPopwindow payPopwindow;
    private UpdateDialog updateDialog;
    private LoginDialog loginDialog;
    private TextView all_order;
    private LinearLayout ll_main;

    private boolean isHuanZhuo = false; //记录是否处于换桌状态
    private HuanZhuoDialog huanZhuoDialog;
    private LoginBean info;
    private ListView lv_menu;
    private TextView tv_type_titile;
    private ListView lv_home;
    private MenuAdapter menuAdapter;
    private HomeAdapter homeAdapter;
    private List<String> data = new ArrayList<>();

    /**
     * 里面存放右边ListView需要显示标题的条目position
     */
    private ArrayList<Integer> showTitle;

    private int currentItem;
    private ArrayList<TabBean> tabBeen;
    private EmptyLayout emptyLayout;
    private SimpleSwipeRefreshLayout refresh;
    private VersionDialog versionDialog;
    private String new_tabId;
    private TextView tv_zhuo;
    private TextView tv_ren;
    private TextView tv_jia;
    private TextView tv_tishi;
    private Intent intent;

    @Override
    public void getData() {
        List<LoginBean.TypeListBean> listBeen;
        if(info!=null){
            listBeen = info.getType_list();
            initData(listBeen);
        }else {
            listBeen = new ArrayList<>();
        }
        menuAdapter = new MenuAdapter(this,listBeen);
        homeAdapter = new HomeAdapter(this, listBeen);
        lv_menu.setAdapter(menuAdapter);
        lv_home.setAdapter(homeAdapter);

        if(listBeen.size() == 0){
            emptyLayout.setErrorType(EmptyLayout.NO_DATA,EmptyLayout.NOT_DATA);
        }
    }

    @Override
    public void setListeners() {
        /**
         * 刷新
         */
        refresh.setOnRefreshListener(() -> {
            onRefreshData(0);
        });
        /**
         * 全部订单
         */
        all_order.setOnClickListener(v -> {
            openActivity(AllOrderActivity.class, null);
        });

/**
 * 餐桌详情
 */
        lv_home.setOnItemClickListener((parent, view, position, id) -> {
            LoginBean.TypeListBean.TabListBean tabListBean = tabBeen.get(position).getTabListBean();
            if(isHuanZhuo){   //换桌操作
                if (!tabListBean.getTab_state().equals("1")) {  //暂停的餐桌
                    ToastUtil.showToast(Main1Activity.this,"请选择空闲餐桌");
                } else {
                    new_tabId = tabListBean.getTab_id();
                    huanZhuoDialog.show();
                }
            }else {
                if (tabListBean.getTab_state().equals("0")) {  //暂停的餐桌
                    ToastUtil.showToast(Main1Activity.this,"已暂停的餐桌不允许开桌，请联系吧台管理员");
                } else if (tabListBean.getTab_state().equals("1")) { //空闲的餐桌
                    updateDialog.setTabListBean(tabListBean);
                    updateDialog.getTv_message().setText("请输入"+tabListBean.getTab_name()+"上客人数");
                    updateDialog.getEt_num().setHint(tabListBean.getTab_name());
                    updateDialog.show();
                } else if (tabListBean.getTab_state().equals("2")) { //使用中的餐桌
                    String type = tabBeen.get(position).getType();
                    Bundle bundle = new Bundle();
                    bundle.putString("tabListBean",tabListBean.getTab_id());
                    bundle.putString("type",type);
                    openActivity(OrderDetailActivity.class, bundle);
                }
            }
        });



        /**
         * 开桌
         */
        updateDialog.setListener((v, text, tabListBean) -> {
                if(!PessmionUtils.check(Main1Activity.this,"1")){
                    return;
                }
                if (text.isEmpty()) {
                    ToastUtil.showToast(Main1Activity.this, "请输入上客人数");
                    return;
                } else {
                    updateDialog.getEt_num().setText("");
                    closeInput(updateDialog.getEt_num());

                    Bundle bundle = new Bundle();
                    bundle.putSerializable("tabListBean", tabListBean);
                    bundle.putString("num", text);
                    openActivity(OpenActivity.class, bundle);
                    updateDialog.cancel();
                }

        });

        /**
         * 换桌提示
         */
        huanZhuoDialog.setOnHZClick(v -> {
            huanzhuo();
        });

        /**
         * 餐桌分类
         */
        lv_menu.setOnItemClickListener((arg0, arg1, arg2, arg3) -> {
            menuAdapter.setSelectItem(arg2);
            menuAdapter.notifyDataSetInvalidated();
            lv_home.setSelection(showTitle.get(arg2));
            tv_type_titile.setText(data.get(arg2));

        });
        lv_home.setOnScrollListener(new AbsListView.OnScrollListener() {
            private int scrollState;

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub
                //System.out.println("onScrollStateChanged" + "   scrollState" + scrollState);
                this.scrollState = scrollState;
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                // TODO Auto-generated method stub
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    return;
                }
                int current =showTitle.indexOf(firstVisibleItem );
//				lv_home.setSelection(current);
                if(currentItem != current && current >=0){
                    currentItem = current;
                    tv_type_titile.setText(data.get(current));
                    menuAdapter.setSelectItem(currentItem);
                    menuAdapter.notifyDataSetInvalidated();
                }
            }
        });
    }
    @Override
    public void initView() {

        intent = new Intent(this,GetInfoService.class);
        startService(intent);
        tv_tishi = (TextView)findViewById(R.id.tv_tishi);
        tv_zhuo = (TextView)findViewById(R.id.tv_zhuo);
        tv_ren = (TextView)findViewById(R.id.tv_ren);
        tv_jia = (TextView)findViewById(R.id.tv_jia);
        all_order = (TextView)findViewById(R.id.all_order);
        lv_menu = (ListView)findViewById(R.id.lv_menu);
        tv_type_titile = (TextView)findViewById(R.id.tv_type_titile);
        lv_home = (ListView)findViewById(R.id.lv_home);
        emptyLayout = (EmptyLayout)findViewById(R.id.emptyLayout);
        refresh = (SimpleSwipeRefreshLayout)findViewById(R.id.refresh);
        refresh.setViewGroup(lv_home);
        refresh.setColorSchemeColors(Color.parseColor("#B41B1B"));

        updateDialog = new UpdateDialog(this);
       //updateDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        updateDialog.getTv_title().setText("开桌");

        ll_main = (LinearLayout)findViewById(R.id.ll_main);

    }

    @Override
    public void initTitle() {
        initPop();
        huanZhuoDialog = new HuanZhuoDialog(this);
        if(TextUtils.isEmpty(CacheConfig.getInst().getWaterToken(this))) {
            loginDialog = new LoginDialog(this);
            loginDialog.setCancelable(false);
            if(versionDialog==null){
                loginDialog.show();
            }else{
                if(!versionDialog.isShowing()){
                    loginDialog.show();
                }
            }

            loginDialog.setListener((v, num, pass) ->
                    login(loginDialog.getEt_num(),loginDialog.getEt_pass(),num,pass));
        }
        iv.setVisibility(View.VISIBLE);
        iv.setOnClickListener(v->{
            if(TextUtils.isEmpty(CacheConfig.getInst().getToken(Main1Activity.this))){
                openActivity(LoginActivity.class,null);
            }else {
                backgroundAlpaha(this, 0.5f);
                payPopwindow.showAsDropDown(iv);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(isHuanZhuo){
            titler.setText("换桌");
            tv_tishi.setText("点击空闲餐桌完成换桌.....");
            tv_tishi.setBackgroundResource(R.color.ffdfdf);
            /// 这一步必须要做,否则不会显示.
            Drawable drawable= getResources().getDrawable(R.mipmap.tishi);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_tishi.setCompoundDrawables(drawable,null,null,null);
        }else{
            titler.setText(info.getName5());
            tv_tishi.setText(R.string.main_tip);
            tv_tishi.setBackgroundResource(R.color.e9e9e9);
            tv_tishi.setCompoundDrawables(null,null,null,null);
        }
    }

    @Subscribe
    public void onEvent(String s){
        if(s.equals(Config.KAIZHUO)){  //换桌
            isHuanZhuo = true;
        }else if(s.equals(Config.REFRESH_LOGIN)){  //登录刷新
            onRefreshData(1);
        }else if(s.equals(Config.LOGIN_SUCCESS)){
            LoginBean loginBean = CacheConfig.getInst().getLogin();
            info = loginBean;
            if(info!=null){
                info.getType_list().get(0).setSelect(true);
            }
            menuAdapter.setData(loginBean.getType_list());
            homeAdapter.setData(loginBean.getType_list());
            initData(loginBean.getType_list());
        }else if(s.equals(Config.BIND_SUCCESS)){
            LoginBean loginBean = CacheConfig.getInst().getLogin();
            info = loginBean;
            if(info!=null){
                info.getType_list().get(0).setSelect(true);
            }
            menuAdapter.setData(loginBean.getType_list());
            homeAdapter.setData(loginBean.getType_list());
            initData(loginBean.getType_list());
        }
    }

//    @Subscribe
//    public void onLogin(LoginBean loginBean){
//        info = loginBean;
//        if(info!=null){
//            info.getType_list().get(0).setSelect(true);
//        }
//        menuAdapter.setData(loginBean.getType_list());
//        homeAdapter.setData(loginBean.getType_list());
//        initData(loginBean.getType_list());
//    }

    public void initData(List<LoginBean.TypeListBean> foodDatas){
        titler.setText(info.getName5());
        if(foodDatas == null || foodDatas.size() == 0){
            emptyLayout.setErrorType(EmptyLayout.NO_DATA,EmptyLayout.NOT_DATA);
            return;
        }else{
            emptyLayout.setVisibility(View.GONE);
        }
        tv_type_titile.setText(info.getType_list().get(0).getType_name());
        tabBeen = new ArrayList<>();

        int tab_nums = 0;
        int tab_peoples = 0;
        double privces = 0;

        for(int i = 0;i<foodDatas.size();i++){
            List<LoginBean.TypeListBean.TabListBean> tab_list = foodDatas.get(i).getTab_list();
            data.add(foodDatas.get(i).getType_name());
            for(int j = 0;j<tab_list.size();j++){
                tabBeen.add(new TabBean(tab_list.get(j),foodDatas.get(i).getType_id(),foodDatas.get(i).getType_name()));

                LoginBean.TypeListBean.TabListBean tabListBean = tab_list.get(j);
                if(tabListBean.getTab_state().equals("2")){
                    tab_nums+=1;

                    List<LoginBean.OrderListBean> order_list = tabListBean.getOrder_list();
                    if(order_list!=null&&order_list.size()!=0){
                        String order_person = order_list.get(0).getOrder_person();
                        int i1 = Integer.parseInt(order_person);
                        tab_peoples+=i1;

                        for(LoginBean.OrderListBean o:order_list){
                            List<LoginBean.OrderListBean.LogListBean> log_list = o.getLog_list();
                            if(log_list!=null){
                                for(LoginBean.OrderListBean.LogListBean logListBean :log_list){
                                    String log_money = logListBean.getLog_money();
                                    privces+=Double.parseDouble(log_money);
                                }
                            }
                        }
                    }
                }

            }
        }

        tv_zhuo.setText(tab_nums+"");
        tv_ren.setText(tab_peoples+"");
        tv_jia.setText("¥"+privces);

        showTitle = new ArrayList<>();
        for(int i = 0; i < tabBeen.size(); i++){
            if( i ==0){
                showTitle.add(i );
            }else if (!TextUtils.equals(tabBeen.get(i).getTitle(), tabBeen.get(i - 1).getTitle())) {
                showTitle.add(i );
            }
        }
    }


    /**
     * 设置添加屏幕的背景透明度
     * **/
    public void backgroundAlpaha(Activity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow()
                .addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }

    @Override
    public void setLayoutView() {
        setContentView(R.layout.activity_main1);
        info = CacheConfig.getInst().getLogin();
        
        EventBus.getDefault().register(this);
        checkUpdate();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
            exitBy2Click(); //调用双击退出函数
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GetInfoService.index = false;
        stopService(intent);
        isHuanZhuo = false;
        EventBus.getDefault().unregister(this);
    }

    private void initPop() {
        payPopwindow = new PayPopwindow(this);
        payPopwindow.setOnDismissListener(
                () -> backgroundAlpaha(Main1Activity.this,1f));
        payPopwindow.setOnItemClick(index->{
                switch (index){
                    case 0:
                        openActivity(LoginActivity.class,null);
                        payPopwindow.dismiss();
                        break;
                    case 1:
                        openActivity(BangdingActivity.class,null);
                        payPopwindow.dismiss();
                        break;
                    case 2:
                        if(!PessmionUtils.check(Main1Activity.this,"5")){
                            payPopwindow.dismiss();
                            return;
                        }
                        openActivity(PessmiseActivity.class,null);
                        payPopwindow.dismiss();
                        break;
                }
        });
    }

    /**
     *
     * @param type  1.需要progressdialog   0.不需要
     */
    private void onRefreshData(int type){

        if(TextUtils.isEmpty(CacheConfig.getInst().getToken(this))){
            ToastUtil.showToast(this,"没有登录！");
            refresh.setRefreshing(false);
            return;
        }

        if(TextUtils.isEmpty(CacheConfig.getInst().getWaterToken(this))){
            ToastUtil.showToast(this,"请绑定工号！");
            refresh.setRefreshing(false);
            return;
        }

        if(type == 1) {
            progressDialog.setMessage("信息加载中...");
            progressDialog.show();
        }

        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token,CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token,CacheConfig.getInst().getWaterToken(this));
        RetrofitFactory.getIntance().refreshData(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                        refresh.setRefreshing(false);
                        emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR,-1);
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {

                        if(loginBean.getIs_success().equals(ConfigMethod.Success)) {
                            loginBean.setShop_token(CacheConfig.getInst().getToken(Main1Activity.this));
                            CacheConfig.getInst().putData(loginBean);
                            info = loginBean;
                            if (info != null) {
                                info.getType_list().get(0).setSelect(true);
                            }
                            menuAdapter.setData(loginBean.getType_list());
                            homeAdapter.setData(loginBean.getType_list());
                            initData(loginBean.getType_list());
                            refresh.setRefreshing(false);
                            progressDialog.cancel();
                        }else{
                            refresh.setRefreshing(false);
                            progressDialog.cancel();
                            initData(null);
                            ToastUtil.showToast(Main1Activity.this,loginBean.getReason());
                        }
                    }
                });
    }


    /**
     * 工号绑定
     */
    private void login(EditText et_login_num,final EditText et_login_pass,String login_num,String login_pass){
        if(TextUtils.isEmpty(ViewGetTextUtils.getEditText(et_login_num,"工号不能为空")))return;
        else login_num = ViewGetTextUtils.getEditText(et_login_num,"工号不能为空");

        if(TextUtils.isEmpty(ViewGetTextUtils.getEditText(et_login_pass,"密码不能为空")))return;
        else login_pass = ViewGetTextUtils.getEditText(et_login_pass,"密码不能为空");

        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token,CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.water_user_name,login_num);
        map.put(ConfigMethod.water_user_pwd,login_pass);
        RetrofitFactory.getIntance().waiter_login(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<WaterInfo>() {
                    @Override
                    public void onStart() {
                        progressDialog.setMessage("绑定中...");
                        progressDialog.show();
                    }

                    @Override
                    public void onCompleted() {
                        progressDialog.cancel();
                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                    }

                    @Override
                    public void onNext(WaterInfo waterInfo) {
                        if(waterInfo.getIs_success().equals(ConfigMethod.Success)){
                            ToastUtil.showToast(Main1Activity.this,waterInfo.getReason());
                            CacheConfig.getInst().putWaterToken(waterInfo.getWaiter_info().getWaiter_token(),Main1Activity.this);
                            CacheConfig.getInst().putWaterInfo(waterInfo.getWaiter_info());
                            CacheConfig.getInst().putWator_per(waterInfo.getWaiter_info().getWaiter_jurisdiction(),Main1Activity.this);
                            loginDialog.cancel();
                            closeInput(et_login_pass);
                        }else{
                            ToastUtil.showToast(Main1Activity.this,waterInfo.getReason());
                        }
                    }
                });
    }

    /**
     * 版本号检测
     */

    public void checkUpdate(){
        versionDialog = new VersionDialog(this);
        versionDialog.setCancelable(false);
        String version = VersionUtils.getVersion();
        RetrofitFactory.getIntance().updateVersion(new HashMap<>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(responseBody -> {
                    boolean isShow = false;
                    try {
                        JSONObject jsonObject = new JSONObject(responseBody.string().toString());
                        String new_version = jsonObject.getString("version");
                        if(!version.equals(new_version)){
                            String href = jsonObject.getString("href");
                            String desc = jsonObject.getString("desc");
                            versionDialog.setMessage(desc);
                            versionDialog.setUrl(href);
                            LoggerUtils.loge("desc:"+desc+",href:"+href);
                            isShow = true;
                        }else{
                            isShow = false;
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    return isShow;
                })
                .subscribe(isShow -> {
                    try {
                        if(isShow){
                            if(loginDialog==null){
                                versionDialog.show();
                            }else{
                                if(!loginDialog.isShowing()){
                                    versionDialog.show();
                                }
                            }
                            versionDialog.setListener(new VersionDialog.OnUpdateListener() {
                                @Override
                                public void onClick(View v, String url) {
                                    upData(url);
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
    }

    private Intent updataService ;
    private static int REQUESTPERMISSION = 110 ;
    public void upData(String url){
        updataService = new Intent(Main1Activity.this,  UpdataService.class);
        updataService.putExtra("url",url);
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
//申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUESTPERMISSION);
            ToastUtil.showToast(Main1Activity.this,"请允许权限进行下载安装");
        }else{
            startService(updataService);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==REQUESTPERMISSION){
            if(permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    if(updataService!=null)
                        startService(updataService);
                }else{
                        ToastUtil.showToast(Main1Activity.this,"没有权限，无法更新");
                }
            }
        }
    }

    /**
     * 换桌
     */
    private void huanzhuo(){
        progressDialog.setMessage("换桌中...");
        progressDialog.show();
        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token,CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token,CacheConfig.getInst().getWaterToken(this));
        map.put(ConfigMethod.order_id, MyApplicatin.order_id);
        map.put(ConfigMethod.tab_id_old,MyApplicatin.tab_id);
        map.put(ConfigMethod.tab_id_new,new_tabId);
        RetrofitFactory.getIntance().upd_table(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                        isHuanZhuo = false;
                        emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR,-1);
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        HttpUtils.check(loginBean, Main1Activity.this, loginBean1 -> {
                            ToastUtil.showToast(Main1Activity.this,loginBean1.getReason());
                            isHuanZhuo = false;  //重置换桌状态
                            onRefreshData(1);
                            titler.setText(info.getName5());
                            tv_tishi.setText(R.string.main_tip);
                            tv_tishi.setBackgroundResource(R.color.e9e9e9);
                            tv_tishi.setCompoundDrawables(null,null,null,null);
                            huanZhuoDialog.cancel();
                        });
                    }
                });
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;



    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            EventBus.getDefault().unregister(this);
            GetInfoService.index = false;
            stopService(intent);
            finish();
            System.exit(0);
        }
    }

}
